<template>
  <div class="register">   
    <el-form ref="Authuser" :model="Authuser" :rules="loginRules" class="register-form" v-if="giteeboolean" v-loading="vloading" element-loading-text="登陆中">
      <h3 class="title">个人算法训练平台--账号绑定</h3>
      <el-form-item prop="user">
        <el-input v-model="Authuser.user" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="Authuser.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
        >
        <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleadduser"
        >
          <span v-if="!loading">确认</span>
          <span v-else>账号绑定中...</span>
        </el-button>
        <div style="float: right;">
          <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
        </div>
      </el-form-item>
    </el-form>

    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form" v-if="userboolean">
      <h3 class="title">个人算法训练平台</h3>
      <el-form-item prop="studentNumber">
        <el-input v-model="registerForm.studentNumber" type="text" auto-complete="off" placeholder="学号">
          <svg-icon slot="prefix" icon-class="Studentnumber" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" type="text" auto-complete="off" placeholder="手机号码">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-row>
        <el-col :span="15">
          <el-form-item prop="email">
            <el-input v-model="registerForm.email" type="text" auto-complete="off" placeholder="电子邮箱">
              <svg-icon slot="prefix" icon-class="mailbox" class="el-input__icon input-icon"/>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5" style="margin-left: 20px;">
          <el-form-item>
            <el-button
              type="primary"  
              @click.native.prevent="validateCodeRegister"
            >
              <span v-if="loading1==false">获取验证码</span>
               <span v-else>发送中...</span>
            </el-button>
          </el-form-item>
        </el-col>  
      </el-row>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          auto-complete="off"
          placeholder="8-20位字符密码"
          @keyup.enter.native="handleRegister"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
        <password-strength v-model="registerForm.password" style="padding-top: 10px;"></password-strength>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          auto-complete="off"
          placeholder="确认密码"
          @keyup.enter.native="handleRegister"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
       <el-form-item prop="invitationCode">
        <el-input v-model="registerForm.invitationCode" type="text" auto-complete="off" placeholder="邀请码">
          <svg-icon slot="prefix" icon-class="Linktrip" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaOnOff">
        <el-input
          v-model="registerForm.code"
          auto-complete="off"
          placeholder="验证码"
          @keyup.enter.native="handleRegister"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <!-- <div class="register-code">
          <img :src="codeUrl" @click="getCode" class="register-code-img"/>
        </div> -->
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleRegister"
        >
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right;">
          <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>个人算法训练平台 © 2021-12 湘ICP备2021019703号-1版权所有 联系方式：17674011342 此平台仅个人学习使用</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, register, callback, giteelogin,adduser } from "@/api/login";
import PasswordStrength from "@/components/drag/PasswordStrength";
import Cookies from 'js-cookie'
export default {
  name: "githirdparty",
  components:{PasswordStrength},
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const emailbur = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入您的邮箱'));
        }else {
          if(this.registerForm.email!== ''){
            if(this.registerForm.email.match(/^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/)){
                callback();
            }else{
               callback(new Error('您的邮箱输入有误'));
            }
          }
        }
    };
    const validatePassword = (rule, value, callback) =>{
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        //6-20位包含字符、数字和特殊字符
        var ls = 0;
        if (this.registerForm.password !== '') {
          if(this.registerForm.password.match(/([a-z])+/)){
            ls++;
          }
          if(this.registerForm.password.match(/([0-9])+/)){
            ls++;
          }
          if(this.registerForm.password.match(/([A-Z])+/)){
            ls++;
          }
          if(this.registerForm.password.match(/([\W])+/) && !this.registerForm.password.match(/(![\u4E00-\u9FA5])+/)){ 
            ls++;
          }
          if(this.registerForm.password.length<6 || this.registerForm.password.length>20 ){
            callback(new Error('要求6-20位字符'));
            ls=0;
          }
          if(this.registerForm.password.match(/([\u4E00-\u9FA5])+/)){
            callback(new Error('不能包含中文字符'));
            ls=0;
          }
          switch (ls) {
            case 0: this.passwordPercent = 0;callback(new Error('数字、小写字母、大写字母以及特殊字符中四选三'));break;
            case 1: this.passwordPercent = 33;callback(new Error('数字、小写字母、大写字母以及特殊字符中四选三'));break;
            case 2: this.passwordPercent = 66;callback(new Error('数字、小写字母 、大写字母以及特殊字符中四选三'));break;
            case 3:
            case 4: this.passwordPercent = 100;break;
            default: this.passwordPercent = 0;break;
          }
        }
        callback();
      }
    };
    return {
      passwordPercent:0,
      codeUrl: "",
      loginForm: {
        username: "",
        uuid: "",
        password: "",
      },
      registerForm: {
        username: "",
        password: "",
        nickname: "",
        confirmPassword: "",
        code: "",
        uuid: "",
        email: "",
        tepy: "",
        studentNumber: "",
        invitationCode: "",
        avatar: "",
      },
      loginRules: {
        user: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ]
      },
      // userForm:{
      //   user: "",
      //   password: "",
      // },
      Authuser:{
        user: "",
        password: "",
        userId:"",
        uuid:"",
        loginName:"",
        userName:"",
        avatar:"",
        email:"",
        source:""
      },
      gitee:{},
      giteeboolean: false,
      userboolean: true,
      redirect: undefined,
      vloading: true,
      registerRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的手机号", pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/ },
          { min: 2, max: 20, message: '用户账号长度必须介于 11 位', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 5, max: 20, validator: validatePassword, trigger: 'blur' }
        ],
        studentNumber: [
          { required: true, trigger: "blur", message: "请输入您的学号" },
          { min: 12, message: '学号长度必须介于 12 位',trigger: 'blur' }
        ],
        invitationCode: [
          { required: true, trigger: "blur", message: "请输入您的邀请码" },
          { trigger: 'blur' }
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入您的邮箱" },
          { min: 5, max: 20, validator: emailbur, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      loading1: false,
      captchaOnOff: true
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getToken();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.data.captchaOnOff === undefined ? true : res.data.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.data.img;
          this.registerForm.uuid = res.data.uuid;
        }
      });
    },
    passwordPercentFormat(percentage){
      return percentage === 100 ? '符合' : `不符`;
    },
    //解析url中的token参数
    getToken(){
      this.userboolean=false
      this.giteeboolean=false
      var url = window.document.location.href.toString();//获得当前url地址并转换成字符串
      var u = url.split("?");//以？来分割字符串，将？前后的值存到一个数组中
      if(typeof(u[1]) == "string"){//获得？后面具体的请求参数值
        u = u[1].split("&");
        var get = {};
        for(var i in u){
          var j = u[i].split("=");
          get[j[0]] = j[1];
        }
        if(get.token!=null){
          this.userboolean=false
          this.giteeboolean=true
          // let token =this.$route.query.token
          Cookies.set('Admin-Token', get.token)
          // this.$router.push("/")
          // token =this.$route.query.token
          Cookies.set('Admin-Token', get.token)
          this.$router.push("/")
        }
        else if(get.uuid!=null){
          this.getCode();
          this.userboolean=false
          this.giteeboolean=true
          this.vloading=false
          this.Authuser.uuid=get.uuid
          this.Authuser.source=get.source
          this.$message.error("该账户没有绑定账号，请绑定账号后重新登陆")
        }
        else{
          this.vloading=false
          this.userboolean=true
          this.giteeboolean=false
          this.$message.error("系统错误，请重新登陆")
          this.$router.push("/login")
        }
      }else{
        this.getCode();
        this.vloading=false
        this.userboolean=true
        this.giteeboolean=false
      }
    },
    handleRegister() {
      this.registerForm.tepy=1;
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true;
          register(this.registerForm).then(response => {
            const username = this.registerForm.username;
            this.Authuser.userId=response.data.sysUser.userId
            this.$alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", '系统提示', {
              dangerouslyUseHTMLString: true
            }).then(() => {
              this.$router.push("/login");
            }).catch(() => {});
          }).catch(() => {
            this.loading = false;
            if (this.captchaOnOff) {
              this.getCode();
            }
          })
        }
      });
    },
    handleadduser(){
      adduser(this.Authuser).then(res=>{
        if(res.code==200){
          // this.$message.source("绑定成功，请重新登陆")
          this.$notify({
            title: '成功',
            message: '"绑定成功，请重新登陆',
            type: 'success'
          });
          this.$router.push("/login");
        }else{
          this.$message.error("绑定失败")
        }
      })
    },
    validateCodeRegister(){
      this.registerForm.tepy=2;
      this.loading1=true
       register(this.registerForm).then(response => {
         if(response.data.Return==2000){
           this.loading1=false
            this.$message({
              message: response.data.Tips,
              type: 'success'
            });
         }
         if(response.data.Return==5000){
            this.loading1=false
            this.$message.error(response.data.Tips);
         }
        // console.log("2222",response)
      }).catch(() => {
            this.loading = false;
            if (this.captchaOnOff) {
              this.getCode();
            }
          });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  display: flex;
  justify-content: center;
  align-items: center;
 	width: 100%;
	height: 100%;
	background: url('https://gitee.com/lyt-top/vue-next-admin-images/raw/master/login/bg-login.png') no-repeat;
	background-size: 100% 100%;
  // background-image: url("../assets/images/login-background.jpg");
  // background-color: azure;
  // background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.register-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #000000;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.register-code-img {
  height: 38px;
}
</style>
